package b3d.parsers
{
	import b3d.core.Object3D;
	import b3d.geometry.Mesh3D;
	import b3d.materials.AmbientLightMaterial;
	
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.registerClassAlias;
	import flash.utils.ByteArray;
	import flash.utils.getTimer;

	public class Parser_b3d extends BaseParser
	{
		
		
		private var data			:ByteArray;
		
		
		public function Parser_b3d(){}		
		
		
		public override function parseFromUrl(url:String, onParseComplete:Function):void
		{
			this.url 				= url;
			this.onParseComplete 	= onParseComplete;
			var loader:URLLoader 	= new URLLoader(new URLRequest(url));
			loader.dataFormat 		= URLLoaderDataFormat.BINARY;
			
			loader.addEventListener(Event.COMPLETE, onLoadComplete);	
		}
		private function onLoadComplete(e:Event):void
		{
			var data:ByteArray = (e.target as URLLoader).data;
			parseFromData(data);
		}
		public function parseFromData(data:ByteArray):void
		{
			this.data = data;
			//data.endian = Endian.LITTLE_ENDIAN;
			var time:int = getTimer();
			data.position = 0;
			data.uncompress();
			registerClassAlias("Mesh3D", Mesh3D)
			mesh = data.readObject() as Mesh3D;
			trace("parse time", getTimer()-time);
			
			objects = new Vector.<Object3D>();
			var object:Object3D = new Object3D().build(mesh, new AmbientLightMaterial(Math.random()*0xFFFFFF));
			objects.push(object);
			
			if(onParseComplete != null) onParseComplete();
		}
	}
}